/**
 * @author hanzc (hanzhichen@baijia.com)
 * @date 2021-01-29
 * fineBi经分退费看板part2: 主讲退费情况
 */
import React, {useState} from 'react';
import {useMount, useSetState} from 'ahooks';
import {Row, Col, Card, Typography} from 'antd';
import {
    querySelectOptions,
    queryValues,
    queryDetail,
    download
} from '~/service/refundReport';
import CommonSearchBar from '../../../common/CommonSearchBar';
import DetailCard from '../../../common/DetailCard';
import DetailModal from '../../../common/DetailModal';
import Loading from '../../../common/Loading';
import {convertSearcherParams} from '../../../utils/convert';
import {searchFormPart2} from '../../config';
import RefundOnTeacherBarChart from './RefundOnTeacherBarChart';

const {Title} = Typography;

const initialValues = {
    // eslint-disable-next-line babel/camelcase
    refund_moment: ['全量'],
};
const DashboardIdPre = 'refundKanbanTwoPart';
const SELECT_UNIT_ID = 'selectUnit_13';
const DashboardCfg1 = [
    {
        dashBoardName: 'refundKanbanTwoPart_partOne',
        dashBoardId: 'refundKanbanTwoPart_partOne'
    }
];

/** fineBi经分退费看板part2: 主讲退费情况 */
const RefundOnTeacherDashBoard = props => {
    const [loading, setLoading] = useState(false);
    const [result, setResult] = useSetState({});
    // searchform
    // searchform中的select, 数据源全部都是动态从后端查询的
    const [selectOptions, setSelectOptions] = useState({});
    const [searchFormValues, setSearchFormValues] = useState(initialValues);
    // detail
    const [detailData, setDetailData] = useState({});
    const [detailModalVisible, setDetailModalVisible] = useState(false);

    // 返回结果是这样的格式
    const {
        refundKanbanTwoPart_partOne: {
            refundKanbanTwoPart_partOne_bar_1: refundOnTeacherBarChartUnit = {}
        } = {}
    } = result;

    /** 查询方法 */
    const getData = (params = {}) => {
        const {
            dashBoardList = [],
            dimensionAndValues = [],
            ...restParams
        } = params;
        setLoading(true);
        Promise.all(
            dashBoardList.map((oneDashboard = {}) => {
                const {dashBoardId = ''} = oneDashboard;
                const newDimensionAndValues = dimensionAndValues.map(
                    ({dimensionId: dimId = '', ...restDAV} = {}) => ({
                        dimensionId: `${dashBoardId}_${dimId}`,
                        ...restDAV
                    })
                );
                return queryValues({
                    dashBoardList: [oneDashboard],
                    dimensionAndValues: newDimensionAndValues,
                    ...restParams
                }).then(res => {
                    const {data = {}} = res;
                    setResult({...data});
                });
            })
        ).finally(() => {
            setLoading(false);
        });
    };

    /** 点击搜索按钮 */
    const handleSearch = params => {
        setSearchFormValues(params);
        const queryParams = {
            dashBoardList: DashboardCfg1,
            dimensionAndValues: convertSearcherParams(params)
        };
        getData(queryParams);
    };
    const handleReset = () => {
        setSearchFormValues(initialValues);
        const queryParams = {
            dashBoardList: DashboardCfg1,
            dimensionAndValues: convertSearcherParams(initialValues)
        };
        getData(queryParams);
    };
    // detail
    // 函数柯里化, 提前记录unit参数
    const handleDetail = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        setDetailModalVisible(true);
        const newDimensionAndValues = convertSearcherParams(
            searchFormValues
        ).map(({dimensionId: dimId = '', ...restDAV} = {}) => ({
            dimensionId: `${dashBoardId}_${dimId}`,
            ...restDAV
        }));
        const params = {
            dimensionAndValues: newDimensionAndValues || [],
            unitId,
            unitName
        };
        queryDetail(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };
    const handleDownload = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        const newDimensionAndValues = convertSearcherParams(
            searchFormValues
        ).map(({dimensionId: dimId = '', ...restDAV} = {}) => ({
            dimensionId: `${dashBoardId}_${dimId}`,
            ...restDAV
        }));
        const params = {
            dimensionAndValues: newDimensionAndValues || [],
            unitId,
            unitName
        };
        const excelName = unitName ? unitName : null;
        download(params, excelName);
    };
    // 请求单个表单配置项
    const handleFetchOptions = ({
        key,
        searchKey,
        pager,
        dependItemKey,
        dependItemValue,
        isGetingMore,
        options: curOptions,
        fieldsValue
    }) => {
        let permissions = searchFormPart2.map(item => ({
            // dimensionId: getDimensionId(0, item.key),
            dimensionId: `${DashboardIdPre}_${item.key}`,
            dimensionName: item.key,
            filterItems: Array.isArray(fieldsValue[item.key])
                ? fieldsValue[item.key]
                : fieldsValue[item.key] == null
                    ? []
                    : [fieldsValue[item.key]]
        }));

        permissions = permissions.filter(item => item.filterItems?.length);

        const params = {
            pager,
            dimensionId: `${DashboardIdPre}_${key}`,
            dimensionName: key,
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    // mount
    useMount(() => {
        const queryParams = {
            dashBoardList: DashboardCfg1,
            dimensionAndValues: convertSearcherParams(initialValues)
        };
        getData(queryParams);
    }, []);

    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchFormPart2}
                    selectOptions={selectOptions}
                    initialValues={initialValues}
                    onOk={handleSearch}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    loading={loading}
                />
            </Card>
            <Card>
                <Row>
                    <Col span={24}>
                        <DetailCard
                            title={refundOnTeacherBarChartUnit?.unitName ?? ''}
                            onDownload={handleDownload(
                                refundOnTeacherBarChartUnit,
                                DashboardCfg1?.[0].dashBoardId
                            )}
                            onDetail={handleDetail(
                                refundOnTeacherBarChartUnit,
                                DashboardCfg1?.[0].dashBoardId
                            )}
                            style={{height: '100%'}}
                        >
                            <Loading loading={loading}>
                                <RefundOnTeacherBarChart
                                    dataSource={refundOnTeacherBarChartUnit}
                                    id="RefundOnTeacherBarChart"
                                />
                            </Loading>
                        </DetailCard>
                    </Col>
                </Row>
            </Card>
            <DetailModal
                data={detailData}
                detailModalVisible={detailModalVisible}
                onCancel={() => setDetailModalVisible(false)}
            />
        </div>
    );
};

export default RefundOnTeacherDashBoard;
